package cfdt.common.utils;


import cn.hutool.core.util.StrUtil;
import cfdt.common.enums.CommonCodeEnum;
import cfdt.common.exception.CodeException;
import cfdt.common.vo.BaseResponse;

/**
 * 通用工具类
 *
 * @author sven.wang
 * @since 2025/8/22 14:16
 */
public class CommonUtils {

    /**
     * 判断请求返回值是不是成功-2000
     * @param response 响应结果
     */
    public static boolean isSuccess(BaseResponse response) {
        if (response == null) {
            return false;
        }

        return response.getCode().equals(CommonCodeEnum.CODE_SUCCESS.getCode());
    }
    /**
     * 判断请求返回值是不是失败
     * @param response 响应结果
     */
    public static boolean isFail(BaseResponse response) {
        return !isSuccess(response);
    }

    /**
     * 响应码描述参数替换
     * @param codeDesc 响应码描述
     * @param args  参数
     */
    public static String getCodeMessage(String codeDesc, Object... args) {
        //参数转字符串
        String[] params = null;
        if (null != args && args.length > 0) {
            params = new String[args.length];
            for (int i = 0; i < args.length; i++) {
                params[i] = args[i] + "";
            }
        }
        String value = codeDesc;

        // 如果有参数，则进行占位符替换
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                value = StrUtil.replace(value, "{" + i + "}", params[i]);
            }
        }
        return value;
    }

    /**
     * 调用rpc接口时，处理响应结果
     * @param response 响应结果
     */
    public static void dealResponse(BaseResponse response) {
        if (response == null) {
            return;
        }
        if (isFail(response)) {
            throw new CodeException(response.getCode(), response.getMessage());
        }
    }
}
